<template>
  <div class="procure-warehouse">
    <!-- 搜索表单 -->
    <div class="search-wrap mt20">
      <SearchForm :list="[...formList]" @submit="search" @reset="reset"></SearchForm>
    </div>

    <!-- 今日/昨日/近7日/近30日等，创建订单按钮，关键词搜索 -->
    <div class="center-search-wrap">
      <div>
        <div class="left">
          <el-button type="primary" @click="clickCreate"> 新建仓库 </el-button>
        </div>
      </div>
    </div>

    <!-- 表单数据 -->
    <el-table class="jzt-table" :data="list" stripe style="width: 100%">
      <el-table-column prop="warehouseNo" show-overflow-tooltip label="仓库编码" width="180" />
      <el-table-column prop="warehouseName" show-overflow-tooltip label="仓库名称" />
      <el-table-column prop="manageUserName" show-overflow-tooltip label="负责人姓名" />
      <el-table-column prop="managePhoneNo" show-overflow-tooltip label="电话" />
      <el-table-column prop="manageEmail" show-overflow-tooltip label="邮箱" />
      <el-table-column prop="status" show-overflow-tooltip label="禁用/启用">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="
              val => {
                currObj = scope.row;
                updateStatusFun(val);
              }
            "
          />
        </template>
      </el-table-column>
      <el-table-column prop="address" show-overflow-tooltip label="省">
        <template #default="scope">
          <span>{{ scope.row.provinceName || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" show-overflow-tooltip label="市">
        <template #default="scope">
          <span>{{ scope.row.cityName || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" show-overflow-tooltip label="区">
        <template #default="scope">
          <span>{{ scope.row.districtName || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" prop="action" label="操作" width="100">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="
              () => {
                currObj = scope.row;
                clickUpd();
              }
            "
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pt20 pb20" style="display: flex; justify-content: flex-end">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="pagination.sizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增、修改弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="actionType === 'add' ? '新建仓库' : '修改仓库'"
      width="500"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <div class="form-wrap">
        <el-form :model="form" ref="formRef" label-width="auto" style="max-width: 600px">
          <el-form-item prop="warehouseName" label="仓库姓名" :rules="{ required: true, message: '请输入', trigger: ['blur'] }">
            <el-input
              v-model="form.warehouseName"
              placeholder="请输入"
              maxlength="15"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
          <el-form-item prop="area" label="仓库地址" :rules="{ required: true, message: '请选择', trigger: ['blur'] }">
            <el-cascader
              placeholder="请选择"
              class="pb10"
              ref="cascaderRef"
              v-model="form.area"
              :options="mapList"
              :props="{
                expandTrigger: 'hover', //次级菜单的展开方式
                label: 'name',
                value: 'id'
              }"
              @change="handleChange"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item prop="address" label="详细地址" :rules="{ required: true, message: '请输入', trigger: ['blur'] }">
            <el-input
              v-model="form.address"
              placeholder="请输入"
              maxlength="50"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
          <el-form-item prop="manageUserName" label="联系人" :rules="{ required: true, message: '请输入', trigger: ['blur'] }">
            <el-input
              v-model="form.manageUserName"
              placeholder="请输入"
              maxlength="15"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
          <el-form-item
            prop="managePhoneNo"
            label="手机号"
            :rules="[
              { required: true, message: '请输入' },
              { pattern: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
          >
            <el-input
              v-model="form.managePhoneNo"
              placeholder="请输入"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
          <el-form-item
            prop="manageEmail"
            label="邮箱"
            :rules="[
              { required: false, message: '请输入' },
              {
                pattern:
                  /^(([^<>()\[\]\\.,;:\s@]+(\.[^<>()\[\]\\.,;:\s@]+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                message: '请输入格式正确的邮箱'
              }
            ]"
          >
            <el-input
              v-model="form.manageEmail"
              placeholder="请输入"
              oninput="value = value.replace(/[!|#|$|%|^|&|*|+|~|`|,|！|￥]/g, '')"
            />
          </el-form-item>
          <el-form-item prop="remark" label="备注">
            <el-input
              :rows="2"
              type="textarea"
              maxlength="200"
              placeholder="请输入"
              v-model="form.remark"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit(actionType)">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from "vue";
import SearchForm from "@/components/SearchForm";
import { Search, RefreshRight } from "@element-plus/icons-vue";
import china from "@/utils/china.json";
import { ListPage, createWarehouse, updateWarehouse, updateStatus } from "@/apis/procure/warehouse";
import { ElMessage } from "element-plus";

const formList = ref([
  {
    label: "仓库编码",
    model: "warehouseNo",
    type: "input",
    labelWidth: "70"
  },
  {
    label: "仓库名称",
    model: "warehouseName",
    type: "input",
    labelWidth: "70"
  },
  {
    label: "状态",
    model: "status",
    type: "select",
    labelWidth: "70",
    data: [
      { label: "停用", value: 0 },
      { label: "启用", value: 1 }
    ]
  }
]);
const formData = ref({});
const list = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const dialogVisible = ref(false);
const actionType = ref("add");
const form = ref({});
const formRef = ref();
const mapList = ref(china);
const currObj = ref({});

watch(
  () => dialogVisible.value,
  val => {
    if (!val) {
      formRef.value.resetFields();
    }
  }
);

onMounted(() => {
  getList();
});

//仓库启用/停用
const updateStatusFun = val => {
  updateStatus({
    warehouseId: currObj.value.warehouseId,
    status: val
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: val === 1 ? "仓库已启用" : "仓库已停用",
        type: "success"
      });
      getList();
    }
  });
};

//点击创建
const clickCreate = () => {
  form.value = {};
  actionType.value = "add";
  dialogVisible.value = true;
};

//点击修改
const clickUpd = () => {
  actionType.value = "upd";
  form.value = JSON.parse(JSON.stringify(currObj.value));
  form.value.area = [form.value.provinceId, form.value.cityId, form.value.districtId];
  dialogVisible.value = true;
};

const submit = type => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      if (type === "add") {
        // 添加
        const _form = JSON.parse(JSON.stringify(form.value));
        delete _form.area;
        createWarehouse(_form).then(res => {
          if (res.code === 200) {
            ElMessage({
              message: "仓库创建成功",
              type: "success"
            });
            getList();
            dialogVisible.value = false;
          }
        });
      } else {
        // 修改
        const _form = JSON.parse(JSON.stringify(form.value));
        delete _form.area;
        updateWarehouse(_form).then(res => {
          if (res.code === 200) {
            ElMessage({
              message: "仓库修改成功",
              type: "success"
            });
            getList();
            dialogVisible.value = false;
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const cascaderRef = ref();
const handleChange = value => {
  console.log("producerList", value);
  const nodes = cascaderRef.value.getCheckedNodes();
  console.log("找到了当前选中的节点数据===", nodes);
  form.value.provinceId = nodes[0].pathValues[0];
  form.value.cityId = nodes[0].pathValues[1];
  form.value.districtId = nodes[0].pathValues[2];
  form.value.provinceName = nodes[0].pathLabels[0];
  form.value.cityName = nodes[0].pathLabels[1];
  form.value.districtName = nodes[0].pathLabels[2];
};

// 关闭新增、编辑弹窗
const handleClose = () => {
  dialogVisible.value = false;
};

//查询入库单列表数据
const getList = () => {
  const params = {
    ...formData.value,
    page: pagination.value.page,
    size: pagination.value.size
  };
  ListPage(params).then(res => {
    if (res.code === 200) {
      list.value = res.data.records;
      pagination.value.total = res.data.total;
    }
  });
};

// 表单查询组件submit回调
const search = form => {
  console.log("查询表单数据===", form);
  if (form) {
    let _form = JSON.parse(JSON.stringify(form));
    // _form.startDate = form?.createTime ? form?.createTime[0] : null;
    // _form.endDate = form?.createTime ? form?.createTime[1] : null;
    // delete _form?.createTime;
    formData.value = _form;
  } else {
    formData.value = {};
  }
  nextTick(() => {
    getList();
  });
};
//清空查询表单
const reset = () => {
  search("");
};

const handleSizeChange = val => {
  pagination.value.size = val;
  getList();
};
const handleCurrentChange = val => {
  pagination.value.page = val;
  getList();
};
</script>

<style lang="scss" scoped>
:deep(.dialog-footer) {
  display: flex;
  justify-content: center;
}
.procure-warehouse {
  height: calc(100% - 20px);
  overflow-y: auto;
  padding: 0 20px 20px 20px;

  .search-wrap {
    padding: 20px;
    overflow-x: hidden;
    background-color: #f6f8fa;
  }

  .center-search-wrap {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 22;
    :deep(.el-input-group__prepend) {
      padding: 0;
      box-shadow: none;
    }
    :deep(.el-input.el-input-group.el-input-group--append.el-input-group--prepend) {
      & > .el-input-group__prepend {
        border-radius: 4px 0 0 4px;
        border: 1px solid #dcdfe6;
        border-right: none;
        .el-input__wrapper {
          border-radius: 4px;
        }
        .el-cascader.el-tooltip__trigger.el-tooltip__trigger {
          border-radius: 4px 0 0 4px;
        }
      }
      & > .el-input__wrapper {
        border: 1px solid #dcdfe6;
      }
    }
    :deep(.el-input__wrapper) {
      box-shadow: none;
    }
    & > div {
      display: flex;
      justify-content: space-between;
      padding: 20px 0;
    }
    & > div > div {
      display: flex;
    }
    .left {
      :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
        background-color: white;
        color: #007dff;
      }
    }
  }
}
</style>
